import 'package:mobx/mobx.dart';
import 'package:hinge/common/models/chat_message_model.dart';
import 'package:hinge/common/models/chat_session_model.dart';
import 'package:hinge/common/models/user_model.dart';
import 'package:hinge/common/services/chat_service.dart';
import 'package:hinge/common/services/user_service.dart';

part 'chat_store.g.dart';

class ChatStore = _ChatStore with _$ChatStore;

abstract class _ChatStore with Store {
  @observable
  bool isLoading = false;

  @observable
  ObservableList<ChatMessageModel> chatMessages =
      ObservableList<ChatMessageModel>.of([]);

  @observable
  ObservableList<UserModel> chatMembers = ObservableList<UserModel>.of([]);

  @observable
  ChatSessionModel? chatSession;

  @action
  Future<void> loadChatDetail(String chatId) async {
    isLoading = true;
    // 获取会话信息
    chatSession = await ChatService.getChatSessionById(chatId);
    // 获取消息列表
    chatMessages.clear();
    chatMessages.addAll(await ChatService.getMessagesForChat(chatId));
    // 获取成员信息
    chatMembers.clear();
    if (chatSession != null) {
      for (var uid in chatSession!.memberIds) {
        final user = UserService.getUserById(uid);
        if (user != null) chatMembers.add(user);
      }
    }
    isLoading = false;
  }

  @action
  Future<void> sendMessage(String text) async {
    if (text.trim().isEmpty || chatSession == null) return;

    // 获取当前用户
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null) return;

    try {
      // 发送消息
      final newMessage = await ChatService.sendMessage(
        chatId: chatSession!.id,
        senderId: currentUser.id,
        type: MessageType.text,
        text: text,
      );

      // 添加消息到列表
      chatMessages.add(newMessage);
    } catch (e) {
      print('发送消息失败: $e');
    }
  }
}
